<template>
  <div class="app-container documentation-container">
    <el-row :gutter="24">
      <el-col :span="8">
        <div>
          <el-statistic :value="numData.departmentNum" title="部门数量" />
        </div>
      </el-col>
      <el-col :span="8">
        <div>
          <el-statistic :value="numData.oneNum" title="父级部门" />
        </div>
      </el-col>
      <el-col :span="8">
        <div>
          <el-statistic :value="numData.delNum" title="回收站(暂时无法恢复)" />
        </div>
      </el-col>
    </el-row>
    <el-divider />

    <div class="custom-tree-container">
      <div class="block department-tree">
        <el-button type="primary" @click="handleAction('change')">添加部门</el-button>
        <p>部门列表</p>
        <el-tree :data="Array.isArray(data)?data:[]" node-key="id" default-expand-all :expand-on-click-node="false">
          <span slot-scope="{ node, data }" class="custom-tree-node" draggable>
            <span class="dept-name" @click="getDeptpeople(data)">{{ data.name }}（{{ data.user_count }}人）</span>
            <span>
              <el-button type="text" size="mini" @click="() => handleAction('edit', data)">
                修改
              </el-button>
              <el-button type="text" size="mini" @click="() => remove(data)">
                删除
              </el-button>
            </span>
          </span>
        </el-tree>
      </div>
      <div class="dept-form">
        <div class="header">
          <el-input
            v-model="params.name"
            clearable
            placeholder="请输入姓名"
            style="width: 30%;"
            size="mini"
            @keyup.enter.native="getDeptpeople"
            @clear="getDeptpeople"
          />
        </div>
        <el-table
          v-loading="loading"
          :header-cell-style="{
            color: '#333',
            background: '#f8f8f9'
          }"
          :data="deptPeople"
          label-position="left"
          height="510"
        >
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column align="header-center" label="性别">
            <template slot-scope="scope">
              <span v-if="scope.row.gender == 1">男</span>
              <span v-if="scope.row.gender == 0">女</span>
              <span v-if="scope.row.gender == 2">不详</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handlerShow(scope.row)">
                <i class="el-icon-view" /> 查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 更换领导 -->
    <el-dialog
      title="领导修改"
      :visible.sync="leaderCheckDialogVisible"
      :close-on-click-modal="false"
      width="40%"
    >
      <div>
        <User @change="leaderCheckChange" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="leaderCheckDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="leaderChangePost">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 更换领导end -->
    <DialogContent
      :title="type === 'create' ? '添加部门' : '编辑部门'"
      :visible.sync="createDialog"
      width="40%"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="deptForm"
        label-width="115px"
        label-position="left"
        style="height: 45vh; overflow: auto"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="deptForm.name" />
        </el-form-item>
        <el-form-item label="部门领导">
          {{ user?.username }}
          <el-button type="text" @click="leaderCheckDialogVisible = true;">选择</el-button>
        </el-form-item>
        <el-form-item label="父级部门">
          <el-cascader
            ref="deptCascader"
            v-model="deptForm.parent_id"
            clearable
            :options="Array.isArray(data)?data:[]"
            placeholder="选择部门"
            :props="{ value: 'id', label: 'name', checkStrictly: true }"
          />
        </el-form-item>
        <el-form-item label="是否为父级部门">
          <el-switch v-model="deptForm.is_directory" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input v-model="deptForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createDialog = false">取 消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="post()">保存</el-button>
      </span>
    </DialogContent>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getDept, getDeptpeople } from '@/api/basic'
import { addDept, editDept, delDept, numDept } from '@/api/dept'
import User from '@/components/Check/User'
import DialogContent from '@/components/DialogContent/index.vue'
import { deepClone } from '@/utils'
export default {
  name: 'Documentation',
  components: {
    User,
    DialogContent
  },
  data() {
    return {
      createDialog: false,
      data: [],
      deptPeople: [],
      kind: 'first',
      numData: {},
      deptForm: {
        leader_id: ''
      },
      user: {},
      leaderCheckDialogVisible: false,
      checkUser: [],
      rules: {
        name: [
          {
            required: true,
            message: '请输入部门名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        description: [
          {
            // required: true,
            message: '请输入部门描述',
            trigger: 'blur'
          }
        ]
      },
      type: 'create',
      btnLoading: false,
      loading: false,
      total: 0,
      params: {
        name: ''
      }
    }
  },
  computed: {
    ...mapGetters(['defaultCompany'])
  },
  created() {
    this.getDepts()
    this.getDeptpeople()
  },
  methods: {
    async getDepts() {
      const res = await getDept()
      this.data = [
        {
          name: this.defaultCompany.name,
          children: res.data,
          id: null,
          user_count: this.getCount(res.data)
        }
      ]

      const numRes = await numDept()
      this.numData = numRes.data
    },
    getCount(list) {
      let count = 0
      for (let i = 0; i < list.length; i++) {
        const cur = list[i]
        count += cur.user_count
        if (cur.children && cur.children.length > 0) {
          count += this.getCount(cur.children)
        }
      }
      return count
    },
    async getDeptpeople(data) {
      this.loading = true
      try {
        console.log(data)
        // this.kind = 'second'
        const date = {
          department_id: data?.id || null,
          ...this.params
        }
        const res = await getDeptpeople(date)
        this.deptPeople = res.data
      } catch (error) {
        console.log('error ------>', error)
      } finally {
        this.loading = false
      }
    },
    handlerShow(data) {
      this.$router.push({
        path: `/personnel-files/show/${data.id}`,
        query: { tag_title: data.username + '-查看', show: true }
      })
    },
    leaderCheckChange(user) {
      console.log(user, 'user')
      const id = user.length < 1 ? '' : user[0].id
      this.deptForm.leader_id = id / 1
      this.checkUser = user
      this.user = user.length < 1 ? { username: '' } : user[0]
    },
    leaderChangePost() {
      // this.user = this.checkUser[0];
      this.leaderCheckDialogVisible = false
    },
    post() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.btnLoading = true
          if (this.deptForm.parent_id && this.deptForm.parent_id.length === 0) {
            delete this.deptForm.parent_id
          }
          if (this.deptForm.parent_id && typeof this.deptForm.parent_id === 'object' && this.deptForm.parent_id.length > 0) {
            this.deptForm.parent_id = this.deptForm.parent_id[this.deptForm.parent_id.length - 1]
          }
          if (this.type == 'create') {
            addDept(this.deptForm)
              .then(() => {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.createDialog = false
                this.getDepts()
                this.change()
              })
              .catch(err => {
                console.log(err)
              })
              .finally(() => {
                this.btnLoading = false
              })
          } else {
            if (this.deptForm.id == this.deptForm.parent_id) {
              this.$message({
                message: '您不可将本部门设为父级部门',
                type: 'warning'
              })
              this.btnLoading = false
              return
            }
            console.log(this.deptForm)
            if (this.user) {
              this.deptForm.leader_id = this.user.id
            }
            editDept(this.deptForm)
              .then(() => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.createDialog = false
                this.getDepts()
                this.change()
              })
              .finally(() => {
                this.btnLoading = false
              })
          }
        } else {
          return false
        }
      })
    },
    handleAction(type, data) {
      this[type](data)
      this.createDialog = true
      // this.type = type
    },
    edit(data) {
      // this.kind = 'first'
      this.type = 'edit'
      this.deptForm = deepClone(data)
      this.user = data.leader
      this.deptForm.is_directory = data.is_directory == 1 ? 1 : 0
    },
    change() {
      // this.kind = 'first'
      this.type = 'create'
      this.deptForm = {}
      this.user = {}
    },
    remove(data) {
      this.$confirm('此操作将删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delDept({
            id: data.id
          }).then(res => {
            if (res.code == 201) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.getDepts()
            } else {
              this.$message({
                message: res.message,
                type: 'warning'
              })
            }
          })
        })
        .catch(() => { })
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-tree-container {
  display: flex;
  justify-content: space-between;

  .block {
    .dept-name {
      font-weight: 700;
      font-size: 14px;
    }
  }
  .department-tree {
    width: 25%;
    margin-right: 50px;
  }

  .dept-form {
    flex: 1;
    .header {
      margin-bottom: 10px;
    }
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
